package com.example.demo.config.one;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import java.lang.reflect.Field;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.List;

/**
 * @author juntao.zhang
 * @version V1.0
 * @Description: TODO
 * @Package com.example.demo.config
 * @date 2018/4/12 22:42
 */
//@Component
@Slf4j
public class HandlerMethodArgumentResolverCompositeRegister implements InitializingBean{

    private final RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    public HandlerMethodArgumentResolverCompositeRegister(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
        this.requestMappingHandlerAdapter = requestMappingHandlerAdapter;
    }



    @Override
    public void afterPropertiesSet() throws Exception {
        MyHandlerMethodArgumentResolverComposite myHandlerMethodArgumentResolverComposite = new MyHandlerMethodArgumentResolverComposite();
        List<HandlerMethodArgumentResolver> argumentResolvers = requestMappingHandlerAdapter.getArgumentResolvers();
        myHandlerMethodArgumentResolverComposite.addResolvers(argumentResolvers);
        MyHandlerMethodArgumentResolverComposite myHandlerMethodArgumentResolverComposite2 = new MyHandlerMethodArgumentResolverComposite();
        List<HandlerMethodArgumentResolver> initBinderArgumentResolvers = requestMappingHandlerAdapter.getInitBinderArgumentResolvers();
        myHandlerMethodArgumentResolverComposite2.addResolvers(initBinderArgumentResolvers);

        log.info("加载MyHandlerMethodArgumentResolverComposite成功:{}",AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> {
            try {
                Field argumentResolversField = requestMappingHandlerAdapter.getClass().getDeclaredField("argumentResolvers");
                argumentResolversField.setAccessible(Boolean.TRUE);
                argumentResolversField.set(requestMappingHandlerAdapter,myHandlerMethodArgumentResolverComposite);
                Field initBinderArgumentResolversField = requestMappingHandlerAdapter.getClass().getDeclaredField("initBinderArgumentResolvers");
                initBinderArgumentResolversField.setAccessible(Boolean.TRUE);
                initBinderArgumentResolversField.set(requestMappingHandlerAdapter,myHandlerMethodArgumentResolverComposite2);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return Boolean.TRUE;
        }));

    }
}
